/* 
*	jQuery文件上传插件,封装UI,上传处理操作采用Baidu WebUploader;
*	@Author 黑爪爪;
*/
(function( $ ) {
	
    $.fn.extend({
		/*
		*	上传方法 opt为参数配置;
		*	serverCallBack回调函数 每个文件上传至服务端后,服务端返回参数,无论成功失败都会调用 参数为服务器返回信息;
		*/
        diyUpload: function (opt, serverCallBack) {
 			if ( typeof opt != "object" ) {
				alert('参数错误!');
				return;	
 			}

 			var UploadBox = $(this);
 			var boxID = UploadBox.attr('id');
 			var boxName = UploadBox.attr('name');
 			var fileBox = UploadBox.find(".fileBox");
 			fileBox.attr("BoxID", boxID);

 			var Code = opt.code;
 			if (opt.code) {
 			    delete opt.code;
 			}

			if( opt.success ) {
				var successCallBack = opt.success;
				delete opt.success;
			}
			
			if( opt.error ) {
				var errorCallBack = opt.error;
				delete opt.error;
			}
			
			//迭代出默认配置
			$.each(getOption('#' + boxID + '_Picker', this.Code), function (key, value) {
			    opt[key] = opt[key] || value;
			});
			
			var url = opt.server;
			if (url.indexOf('?') > 0) {
			    opt.server = opt.server + "&Code=" + Code;
			} else {
			    opt.server = opt.server + "?Code=" + Code;
			}

			if (opt.buttonText ) {
				opt['pick']['label'] = opt.buttonText;
				delete opt.buttonText;	
			}

			var files = null;
			if (opt.files) {
			    files = opt.files;
			    delete opt.files;
			}

			var webUploader = new WebUploader.Uploader(opt);
			
			if ( !WebUploader.Uploader.support() ) {
				alert( ' 上传组件不支持您的浏览器！');
				return false;
			}
		

			if (files) {
			    $.each(files, function (i, v) {
			        createBox(fileBox, v, webUploader);
			    });
			}
			if (opt.isEdit == false) {
			    $('#' + boxID + '_Picker').hide();
			    fileBox.find(".diyCancel").remove();
			}

			//绑定文件加入队列事件;
			webUploader.on('fileQueued', function( file ) {
			    createBox(fileBox, file, webUploader);
			});
			
			//进度条事件
			webUploader.on('uploadProgress', function (file, percentage) {

			   var boxID = fileBox.attr("BoxID");

                //设置上传进度
			   var fileItem = $('#'+  boxID + '_fileItem_' + file.id);
			    var diyBar = fileItem.find('.diyBar');
			    diyBar.show();

				percentage = percentage*100;
				showDiyProgress(percentage.toFixed(2), diyBar);
				
			});
			
			//全部上传结束后触发;
			webUploader.on('uploadFinished', function(){
			    

			});
			//绑定发送至服务端返回后触发事件;
			webUploader.on('uploadAccept', function( object ,data ){
				if ( serverCallBack ) serverCallBack( data );
			});
			
			//上传成功后触发事件;
			webUploader.on('uploadSuccess', function (file, response) {

			    var boxID = fileBox.attr("BoxID");
                //隐藏进度框
			    var fileItem = $('#' + boxID + '_fileItem_' + file.id);
			    var diyBar = fileItem.find('.diyBar')
			    diyBar.hide();

			    //保存文件保存ID
			    var fileItemKey = fileItem.find('.diyFileKey');
			    fileItemKey.val(response.fileKey);

				if ( successCallBack ) {
					successCallBack( response );
				}
			});
			
			//上传失败后触发事件;
			webUploader.on('uploadError', function (file, reason) {

			    var boxID = fileBox.attr("BoxID");

			    var fileItem = $('#' + boxID + '_fileItem_' + file.id);
			    var diyBar = fileItem.find('.diyBar');
			    showDiyProgress(0, diyBar, '上传失败!');

				var err = '上传失败! 文件:'+file.name+' 错误码:'+reason;
				if ( errorCallBack ) {
					errorCallBack( err );
				}
			});
			
			//选择文件错误触发事件;
			webUploader.on('error', function( code ) {
				var text = '';
				switch( code ) {
					case  'F_DUPLICATE' : text = '该文件已经被选择了!' ;
					break;
					case  'Q_EXCEED_NUM_LIMIT' : text = '上传文件数量超过限制!' ;
					break;
					case  'F_EXCEED_SIZE' : text = '文件大小超过限制!';
					break;
					case  'Q_EXCEED_SIZE_LIMIT' : text = '所有文件总大小超过限制!';
					break;
					case 'Q_TYPE_DENIED' : text = '文件类型不正确或者是空文件!';
					break;
					default : text = '未知错误!';
 					break;	
				}
            	alert( text );
			});
			
            ///获取文件数据
			this.FileData = function () {
			    var rtnArr = [];
			    fileBox.find(".diyUpload").each(function (i, v) {
			        var fileText = $(v).find(".diyFileText").val();
			        var fileKey = $(v).find(".diyFileKey").val();
			        var fileCode = $(v).find(".diyFileCode").val();
			        var diyData = $(v).find(".diyFileData").val();
			        
			        if (fileCode == "") {
			            fileCode = Code;
			        }
			        rtnArr.push(boxName + "[" + i + "].ID=" + fileKey);
			        rtnArr.push(boxName + "[" + i + "].Code=" + fileCode);
			        rtnArr.push(boxName + "[" + i + "].DataID=" + diyData);
			        rtnArr.push(boxName + "[" + i + "].FileText=" + escape(fileText));
			    });
			    return rtnArr.join("&");
			};
            if (typeof(gFormPostFun)!="undefined") {
                gFormPostFun.push(this.FileData);
            }
			return this;
        }
    });
	
	//Web Uploader默认配置;
	function getOption(objId) {
		/*
		*	配置文件同webUploader一致,这里只给出默认配置.
		*	具体参照:http://fex.baidu.com/webuploader/doc/index.html
		*/
	    return {
	        auto: true,
	        // swf文件路径
	        swf: '/Content/Upload/images/Uploader.swf',
			//按钮容器;
			pick:{
				id:objId,
				label:" "
			},
			//类型限制;
			accept:{
				title:"Images",
				extensions:"gif,jpg,jpeg,bmp,png",
				mimeTypes:"image/*"
			},
			//配置生成缩略图的选项
			thumb:{
				width:170,
				height:150,
				// 图片质量，只有type为`image/jpeg`的时候才有效。
				quality:70,
				// 是否允许放大，如果想要生成小图的时候不失真，此选项应该设置为false.
				allowMagnify:false,
				// 是否允许裁剪。
				crop:true,
				// 为空的话则保留原有图片格式。
				// 否则强制转换成指定的类型。
				type:"image/jpeg"
			},
			//文件上传方式
			method:"POST",
			//服务器地址;
			server: "../../sys/upload/upload",
			//是否已二进制的流的方式发送文件，这样整个上传内容php://input都为文件内容
			sendAsBinary:false,
			// 开起分片上传。 thinkphp的上传类测试分片无效,图片丢失;
			chunked:false,
			// 分片大小
			chunkSize:512 * 1024,
			//最大上传的文件数量, 总文件大小,单个文件大小(单位字节);
			fileNumLimit:50,
			fileSizeLimit: 102400 * 1024,
			fileSingleSizeLimit:10240 * 1024
		};
	}


	//操作进度条;
	function showDiyProgress( progress, diyBar, text ) {
		
		if ( progress >= 100 ) {
			progress = progress + '%';
			text = text || '上传完成';
		} else {
			progress = progress + '%';
			text = text || progress;
		}
		
		var diyProgress = diyBar.find('.diyProgress');
		var diyProgressText = diyBar.find('.diyProgressText');
		diyProgress.width( progress );
		diyProgressText.text( text );
	}


    //设置上传按钮
	function refreshAdd(fileBox, webUploader) {
	    if (webUploader.options["isEdit"] == false) {
	        return;
	    }
        var filePicker = fileBox.next(".fileAdd"); //获取上传按钮

	    if (fileBox.children('.diyUpload').length >= webUploader.options["fileNumLimit"]) {
	        filePicker.hide();
	    } else {
	        filePicker.show();
	    }
	}

	//取消事件;	
	function removeFile(fileBox, file_id, webUploader) {
	    var boxID = fileBox.attr("BoxID");
	    var fileItem = $("#" + boxID + "_fileItem_" + file_id);
	    if (fileItem.attr("isEdit") == "false") {
	        webUploader.removeFile(file_id);
	    }
        fileItem.remove();
	    refreshAdd(fileBox, webUploader);
	}
	

	//创建文件操作div;	
	function createBox(fileBox, file, webUploader) {
		var file_id = file.id;
		var boxID = fileBox.attr("BoxID");
		var isEdit = webUploader.options["isEdit"];


	    //添加子容器; <a href="' + file.thumb + '" >
		var htmlStr = '<div id="' + boxID + '_fileItem_' + file_id + '" class="diyUpload"  isEdit="' + (file.fileKey ? true : false) + '">';
		htmlStr += '<div class="viewThumb" filePath="' + file.thumb + '"></div>';
		if (isEdit == false) {
		    htmlStr += '<div class="diyFileShow" id="' + boxID + '_fileText_' + file_id + '">' + (file.fileText ? file.fileText : file.name) + '</div>';
		} else {
		    htmlStr += '<div class="diyCancel"></div>';
		    htmlStr += '<textarea class="diyFileText" id="' + boxID + '_fileText_' + file_id + '">' + (file.fileText ? file.fileText : file.name) + '</textarea>';
		    htmlStr += ' <input type="hidden" class="diyFileKey" id="' + boxID + '_fileKey_' + file_id + '" value="' + (file.fileKey ? file.fileKey : "") + '"/>';
		    htmlStr += ' <input type="hidden" class="diyFileCode" id="' + boxID + '_fileCode_' + file_id + '" value="' + (file.code ? file.code : "") + '"/>';
		    htmlStr += ' <input type="hidden" class="diyFileData" id="' + boxID + '_fileData_' + file_id + '" value="' + (file.filedata ? file.filedata : "") + '"/>';
		    htmlStr += '<div class="diyBar">';
		    htmlStr += '<div class="diyProgress"></div> ';
		    htmlStr += '<div class="diyProgressText">0%</div> ';
		    htmlStr += '</div> ';
		}
		htmlStr += '</div>';

		var fileItem = $(htmlStr)
		fileBox.append(fileItem);


		fileItem.children('.viewThumb').on('click', function () {
		    var aimg = this;
		    if (file.type.split("/")[0] != 'image') {
		        window.open($(this).attr("filePath"));
		    }else{
		        var imgs = [];
		        var imgidx = 0;
		        // window.open($(this).attr("filePath"));
		        $(aimg).closest(".fileBox").find("img").each(function (i, v) {
		            if ($(v).attr("src") == $(aimg).attr("filepath")) {
		                imgidx = i;
		            }
		            imgs.push({ "href": $(v).attr("src"), "title": $(v).attr("alt") });
		        });
		        window.top.ShowPhotoView({ "index": imgidx, "pics": imgs });
		    }
		});

		//绑定取消事件;
		var diyCancel = fileItem.children('.diyCancel').one('click', function () {
		    removeFile(fileBox, file_id, webUploader);
		});
		
		refreshAdd(fileBox, webUploader);

		if (file.type.split("/")[0] != 'image') {
			var liClassName = getFileTypeClassName( file.name.split(".").pop() );
			fileItem.addClass(liClassName);
			return;	
		}
		
		if (file.thumb) {
		    fileItem.find('.viewThumb').append('<img src="' + file.thumb + '" alt="' + (file.fileText ? file.fileText : file.name) + '" />');
		} else {
		    //生成预览缩略图;
		    webUploader.makeThumb(file, function (error, dataSrc) {
		        if (!error) {
		            fileItem.find('.viewThumb').append('<img src="' + dataSrc + '" alt="' + (file.fileText ? file.fileText : file.name) + '"/>');
		        }
		    });
		}
	}
	
	//获取文件类型;
	function getFileTypeClassName ( type ) {
		var fileType = {};
		var suffix = '_diy_bg';
		fileType['pdf'] = 'pdf';
		fileType['zip'] = 'zip';
		fileType['rar'] = 'rar';
		fileType['csv'] = 'csv';
		fileType['doc'] = 'doc';
		fileType['xls'] = 'xls';
		fileType['xlsx'] = 'xls';
		fileType['txt'] = 'txt';
		fileType = fileType[type] || 'txt';
		return 	fileType+suffix;
	}
	
})( jQuery );